//
//  LKUserInforViewModel.swift
//  新浪微博
//
//  Created by 胡不归是大虾 on 16/9/26.
//  Copyright © 2016年 胡不归是大虾. All rights reserved.
//

import UIKit
//网络请求
class LKUserInforViewModel: NSObject {
    //创建单例对象
    static let sharedUserInfoViewModel : LKUserInforViewModel = LKUserInforViewModel()
    //MARK:判断用户是否登录
    var userInfoModel :LKUserInfoModel? {
        didSet{
             //在构造函数中给属性赋值 不会执行到 didSet,所以一开始加载没有头像
            let urlString = userInfoModel?.avatar_large ?? ""
            iconUrl = URL(string:urlString)
        }
    }
    //判断是否过期
    var isExpired: Bool {
        if  userInfoModel?.expires_date?.compare(Date()) == ComparisonResult.orderedDescending{
            return false
        }
        return true
    }
    //判断是否登录
    var isLogin : Bool {
        if userInfoModel?.access_token != nil && isExpired == false {
            return true
        }
        return false
    }
    override init() {
        userInfoModel = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? LKUserInfoModel
        let urlString = userInfoModel?.avatar_large ?? ""
        iconUrl = URL(string:urlString)
    }
    //MARK:设置属性接收用户头像的url
    var iconUrl: URL?
    //MARK:网络请求方法
    internal func loadAccessTokem(code:String, finishedClosure:@escaping ((Bool)->())) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id,
                          "client_secret": client_secret,
                          "grant_type": "authorization_code",
                          "code": code,
                          "redirect_uri": redirect_uri]
        LKNetworkTool.sharedTool.request(method: .Post, urlString: urlString, parameters: parameters) { (responseObject, error) in
            //如果error不为空,说明请求出错
            if error != nil {
                print(error)
                finishedClosure(false)
                return
            }
            //解析数据
            print(responseObject)
            //请求用户数据
            self.loadUserInfo(dict: responseObject as! [String : Any],finishedClosure: finishedClosure)
        }
    }
    private func loadUserInfo ( dict: [ String : Any ], finishedClosure:@escaping ((Bool)->())) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token": dict["access_token"]!,"uid": dict["uid"]!]
        LKNetworkTool.sharedTool.request(method: .Get, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil{
                print(error)
                finishedClosure(false)
                return
            }
            //转成字典
            var userInfoDict = responseObject as! [String : Any]
            //字典合并
            for keyValues in dict{
                userInfoDict[keyValues.key] = keyValues.value
            }
            //字典转模型
            let userInfoModel = LKUserInfoModel(dict: userInfoDict)
            //赋值
            self.userInfoModel = userInfoModel
            //归档
            NSKeyedArchiver.archiveRootObject(userInfoModel, toFile: path)
            finishedClosure(true)
        }
    }

}
